package data;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;

import static conf.Configuration.*;

/**
 * Reads in the courses from a given course file.
 * @author Frans Honig, Maxime Serrano, Raphael Townshend
 */
public class CourseDataReader
{
	/**
	 * Position in the file of the course name in every line.
	 */
	private static final int COURSE_NAME_POS = 0;
	
	/**
	 * Position in the file of the course caps in every line.
	 */
	private static final int COURSE_CAP_POS = 1;
	
	/**
	 * Position in the file of the gender balance request in every line.
	 */
	private static final int GENDER_BALANCE_REQUESTED_POS = 2;
	
	/**
	 * The string that allows you to detect a gender-balanced class.
	 */
	private static final String YES_STRING = "Yes";
	
	/**
	 * Delimiter.
	 */
	private static final String DELIMITER = ",";
	
	/**
	 * The courses that have currently been read in.
	 */
	private ArrayList<Course> courses = new ArrayList<Course>();
	
	/**
	 * The name of the file to read in from.
	 */
	private final String fileName;
	
	/**
	 * Creates a new data reader using the default file name. This default is "KS_Course_Caps.csv".
	 */
	public CourseDataReader()
	{
		this.fileName = DEFAULT_COURSE_FILE_NAME;
	}
	
	/**
	 * Creates a new data reader using the given file name.
	 * @param fileName The .csv file to read in course data from.
	 */
	public CourseDataReader(String fileName)
	{
		this.fileName = fileName;
	}

	/**
	 * Creates the ArrayList of courses in order to begin the reading.
	 */
	public void read()
	{
		Scanner s = null;
		try
		{
			s = new Scanner(new BufferedReader(new FileReader(fileName)));
			while(s.hasNext())
			{
				String[] line = s.nextLine().split(DELIMITER);
				String courseName = line[COURSE_NAME_POS];
				int courseCap = Integer.parseInt(line[COURSE_CAP_POS]);
				boolean genderBalanceRequested = line[GENDER_BALANCE_REQUESTED_POS].equals(YES_STRING);
				
				Course c = new Course(courseName, courseCap, genderBalanceRequested);
				courses.add(c);
			}
		}
		catch (FileNotFoundException e) // Uh-oh
		{
			System.err.println("Course data input file not found!");
			e.printStackTrace();
		}
		catch (Exception e)
		{
			System.err.println("Unknown exception occurred while reading course data.");
			e.printStackTrace();
		}
		finally
		{
			if (s != null)
			{
				s.close();
			}
		}
	}
	
	/**
	 * Returns a new copy of the read data as an array list.
	 * @return An array list of all courses that have currently been read in.
	 */
	public ArrayList<Course> getAsList()
	{
		return new ArrayList<Course>(courses);
	}
}
